//
//  NSObject+ZXAvoidCrashKeyValue.m
//  ZXAvoidCrash
//
//  Created by 朱新明 on 2023/9/5.
//

#import "NSObject+ZXAvoidCrashKeyValue.h"
#import "ZXAvoidCrashRuntime.h"
#import "ZXAvoidCrashReport.h"

@implementation NSObject (ZXAvoidCrashKeyValue)

+ (void)zx_avoidCrashExchangeMethod{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //setValue:forKey:
        [ZXAvoidCrashRuntime exchangeInstanceMethodWithClass:[self class] originalSelector:@selector(setValue:forKey:) swizzledSelector:@selector(zx_avoidCrashsetValue:forKey:)];
        //valueForKey:
        [ZXAvoidCrashRuntime exchangeInstanceMethodWithClass:[self class] originalSelector:@selector(valueForKey:) swizzledSelector:@selector(zx_avoidCrashvalueForKey:)];
    });
}



///- (void)setValue:(nullable id)value forKey:(NSString *)key;
///*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[CHSArrayCrashController setValue:forKey:]: attempt to set a value for a nil key'
- (void)zx_avoidCrashsetValue:(nullable id)value forKey:(NSString *)key
{
    @try {
         [self zx_avoidCrashsetValue:value forKey:key];
    } @catch (NSException *exception) {
        [ZXAvoidCrashReport crashReportWithException:exception avoidCrashHandleType:AvoidCrashHandleType_doNothing];
    } @finally {
    }
}

  
///*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<CHSViewController 0x7faaea707810> valueForUndefinedKey:]: this class is not key value coding-compliant for the key keyValueCodingArray.'
- (nullable id)zx_avoidCrashvalueForKey:(NSString *)key
{
    id value = nil;
    @try {
        value = [self zx_avoidCrashvalueForKey:key];
    } @catch (NSException *exception) {
        [ZXAvoidCrashReport crashReportWithException:exception avoidCrashHandleType:AvoidCrashHandleType_returnNil];
    } @finally {
        return value;
    }
}
@end
